<%@ page language="java"
import="java.util.*"
import="javax.imageio.*"
import="java.util.*"
import="javax.xml.*"
import="javax.xml.parsers.*"
import="org.w3c.dom.*"
import="javax.xml.transform.*"
import="javax.xml.transform.dom.*"
import="javax.xml.transform.stream.*" 
import="java.io.StringReader" 
import="java.lang.Integer"
import="org.xml.sax.InputSource"
import="webxml.xmlcmd"
import="webxml.Base64"
import="webxml.logfile"
import="javax.servlet.*" 
import="java.net.URLEncoder"
import="java.io.ByteArrayOutputStream"
import="java.io.BufferedWriter"
import="java.io.FileWriter"
pageEncoding="UTF-8"
contentType="text/xml;charset=utf-8"
%>
<jsp:directive.page import="java.io.File"/>
<jsp:directive.page import="java.io.FileOutputStream"/>
<jsp:directive.page import="java.io.BufferedWriter"/><%!
		
		public static String check_nodlist(NodeList nodeLists , Document docs ,String authkey, String channelid) throws Exception {
		String returnxml = new String("");
		for (int i = 0; i < nodeLists.getLength(); i++) {
			if (check_onenode(nodeLists.item(i), docs) == true) {
			
				{
				Node tmpnode = nodeLists.item(i);
				//Element root=docs.getDocumentElement(); 
				
				Element  onechile = docs.createElement("keyauth");	
				tmpnode.appendChild(onechile);			
				onechile.appendChild(docs.createTextNode( authkey )); 
				
				
	 			}
	 			
	 			{
	 			Node tmpnode = nodeLists.item(i);
				//Element root=docs.getDocumentElement(); 
				
				Element  onechile = docs.createElement("channelid");	
				tmpnode.appendChild(onechile);			
				onechile.appendChild(docs.createTextNode( channelid )); 
				
				
				//Node onechile2 = docs.createElement("channelid");
				//docs.appendChild(onechile2); 				
				//onechile2.appendChild(docs.createTextNode( channelid )); 
				
				}
				returnxml += covertNodeToString(nodeLists.item(i));
			}
		}
		return returnxml;
	}

	public static boolean check_onenode(Node OneNode, Document docs) throws Exception {

		boolean result = true;
		NodeList nodlist;
		try {
			
			if (OneNode.getNodeName().equals("xmlcmd")) {
			
				if (! check_onexmlnode(OneNode, "username")) {				
					throw new Exception();
				}
				
				if ( ! check_onexmlnode(OneNode, "receive")) {				
					throw new Exception();
				}
				
				if ( ! check_onexmlnode(OneNode, "codes")) {
					throw new Exception();				
				}
				
				if ( ! check_onexmlnode(OneNode, "currtime")) {				
					throw new Exception();
				}
				
				
				if ( ! check_onexmlnode(OneNode, "msg") ) {
				
					throw new Exception();
				}
				
				if ( check_onexmlnode(OneNode, "keyauth") ) {
					throw new Exception();				
				}	
				
				if ( check_onexmlnode(OneNode, "channelid") ) {
					throw new Exception();				
				}			
				
			}
		} catch (Exception e) {
			result = false;
		}

		return result;
	}
	
	public static boolean check_onexmlnode(Node OneNode, String a) throws Exception
	{
		NodeList alist; 
		boolean result = false;
		try {
			alist = OneNode.getChildNodes();
			int number;

			for (int i =0 ; i < alist.getLength();i++) {
				Node tmpnode = alist.item(i);
				if (a.equals(tmpnode.getNodeName())){					
					result = true;
					String xx = "";
					if (tmpnode.getFirstChild() != null){
						xx = tmpnode.getFirstChild().getTextContent();
					}
					
					if ((xx!= null) && xx.length() > 64*1024) {
						throw new Exception();
					} else {
						result = true;
					}
				}
		
			}
		}
		catch(Exception e) {
			result = false;
		}
		return result;
	}

	public static String covertNodeToString(Node node)
			throws TransformerFactoryConfigurationError, TransformerException {
		Transformer transformer = TransformerFactory.newInstance()
				.newTransformer();
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");

		DOMSource source = new DOMSource(node);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		transformer.transform(source, new StreamResult(baos));
		String xmlreuslt = String.valueOf(baos);
		return xmlreuslt;
	}%><%
			String outxml ="";
			try {
				response.addHeader("pragma", "no-cache");
				response.addHeader("cache-control", "no-cache");
				response.addHeader("expires", "0");
				//boolean result = true;
				{
					Boolean xx = (Boolean) session.getAttribute("logined");
					if (xx == null || xx.booleanValue() == false) {
						throw new Exception();
					}
				}
				{
					Integer userid = (Integer) session.getAttribute("UserId");

					if (userid == null)
						throw new Exception();
					Object lastfreshtime = session
							.getAttribute("UserFreshTime");
					if (lastfreshtime == null)
						throw new Exception();

					Date Datefresh = (Date) session
							.getAttribute("UserFreshTime");
					Date DateNow = new Date();
					// 刷新时间过长
					if (Datefresh != null) {

						if (DateNow.getTime() - Datefresh.getTime() > xmlcmd.freshmaxtime * 1000) {
							Boolean b = new Boolean(false);
							//(Boolean)session.getAttribute("logined");
							session.setAttribute("logined", b);
							throw new Exception();
						}

						session.setAttribute("UserFreshTime", DateNow);
					} else {
						throw new Exception();
					}
				}

				//session.getAttribute("");
				String xmlfile = request.getParameter("xmlfile");
				if (xmlfile == null || xmlfile.length() == 0) {
					throw new Exception();
				}
				xmlfile = Base64.decode(xmlfile);
				String freshfilename  = "fresh_get.txt";
			
				logfile.writelog( freshfilename, xmlfile );
				
				// 测试clientcmd_array
				ServletContext Application = getServletContext();
				xmlcmd[] value = (xmlcmd[]) Application
						.getAttribute("ClientCmd_Array");
				if (value == null) {
					throw new Exception();
				}

				DocumentBuilderFactory factory = DocumentBuilderFactory
						.newInstance();
				DocumentBuilder builder = factory.newDocumentBuilder();
				Document document = builder.parse(new InputSource(
						new StringReader(xmlfile)));

				NodeList nodeLists = document.getElementsByTagName("xmlcmd");
				
				
				String aukey = (String)session.getAttribute("keyauth");
				if (aukey == null) 
				{
				 throw new  Exception(); 
				}
				
				Integer chid = (Integer) session.getAttribute("channelid");
				if (chid == null) 
				{
				 throw new  Exception();
				}	
				String channelid = chid.toString();
	
				outxml = check_nodlist(nodeLists, document, aukey, channelid );

				//lock application
				
				synchronized (Application) {

					Integer userid = (Integer) session.getAttribute("UserId");
					int x = userid.intValue();
					String autherid = (String) session.getAttribute("keyauth");
					Integer bb = new Integer(value[x].userkey);
					// 判读
					if (!autherid.equals(bb.toString())) {
						Boolean b = new Boolean(false);
						session.setAttribute("logined", b);
						throw new Exception();
					}					
					
					if (value[x].cmdsize == 0) {
						value[x].cmdsize += 1;	
					}
						value[x].onexmlcmd[value[x].cmdsize-1] += outxml;						
						Application.setAttribute("ClientCmd_Array", value);
						outxml = "";
					
					
					xmlcmd[] Servervalue = (xmlcmd[]) Application
						.getAttribute("ServerCmd_Array");
					if (Servervalue == null) {
						throw new Exception();
					}
					outxml = "";
					for (int i = 0; i < Servervalue[x].cmdsize; i++) {
						outxml += Servervalue[x].onexmlcmd[i];
						Servervalue[x].onexmlcmd[i] = "";
					}
					Servervalue[x].cmdsize = 0;
					Application.setAttribute("ServerCmd_Array", Servervalue);								
				}
				
			} catch (Exception e) {
				out.print(e.getMessage());
			}
		    outxml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><root>" + outxml;
		    outxml += "</root>";
		    String filename  = "fresh_out.txt";
			
			logfile.writelog( filename, outxml );

//		    java.io.File logfile = new java.io.File(filename);
		    
//		    if (! logfile.exists())
		    {
//		    	logfile.createNewFile();		    
		    }
		    {
//		    	java.io.PrintWriter pw = new java.io.PrintWriter( new BufferedWriter (new FileWriter(logfile), true));
//		    	pw.println(outxml);
		    	
//		    	pw.close();
		    }
//	    
	
				   
		    out.print(Base64.encode(outxml));
			//out.print(outxml);
			//out.print("</root>");%>
